﻿using System;
using System.Net;
using System.Net.Sockets;

namespace CSharpHelpers.Nets
{
    /// <summary>
    /// IP帮助类
    /// </summary>
    public static class IPHelper
    {
        public static string GetLocalIP()
        {
            string ip = String.Empty;
            IPAddress[] addresses = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            foreach (IPAddress ipAdd in addresses)
            {
                if (ipAdd.AddressFamily.Equals(AddressFamily.InterNetwork))
                {
                    ip = ipAdd.ToString();
                    break;
                }
            }
            return ip;
        }

        public static IPAddress[] GetLocalIp()
        {
            string name = Dns.GetHostName();
            IPHostEntry me = Dns.GetHostEntry(name);
            return me.AddressList;
        }

        public static IPAddress GetFirstIp()
        {
            IPAddress[] ips = GetLocalIp();
            foreach (IPAddress ip in ips)
            {
                if (ip.AddressFamily == AddressFamily.InterNetworkV6)
                    continue;
                return ip;
            }
            return ips != null && ips.Length > 0 ? ips[0] : new IPAddress(0x0);
        }
    }
}
